package com.tarena.lbs.basic.web.service.impl;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.BasePageList;
import com.tarena.lbs.basic.web.repoistory.UserGroupRepository;
import com.tarena.lbs.basic.web.repoistory.UserRepository;
import com.tarena.lbs.basic.web.repoistory.UserTagRepository;
import com.tarena.lbs.basic.web.service.AdminService;
import com.tarena.lbs.basic.web.service.UserService;
import com.tarena.lbs.common.basic.util.RandomUserName;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.common.security.utils.LbsSecurityContenxt;
import com.tarena.lbs.pojo.basic.bo.AdminBO;
import com.tarena.lbs.pojo.basic.bo.UserBO;
import com.tarena.lbs.pojo.basic.bo.UserGroupBO;
import com.tarena.lbs.pojo.basic.param.UserTagsParam;
import com.tarena.lbs.pojo.basic.query.UserGroupQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserTagRepository userTagsRepository;
    @Autowired
    private UserGroupRepository userGroupRepository;
    @Autowired
    private AdminService adminService;

    @Override
    public void saveUser(UserBO userBO) {
          /*
          private Integer status;业务补充 0 正常 没有绑定标签 1已经绑定标签
          private String userName; 业务默认一个随机
          private String nickName; userName一致
          private Date regTime; 相当于创建时间 业务补充
          上述几个字段在业补充 写入数据库
          */
        //填补 默认status 0
        userBO.setStatus(0);
        userBO.setUserName(RandomUserName.createRandomName());
        userBO.setNickName(userBO.getUserName());
        userBO.setRegTime(new Date());
        userRepository.saveUser(userBO);
    }

    @Override
    public UserBO userDetail() throws BusinessException {
        //1. 获取登录用户id
        UserPrinciple userPrinciple = LbsSecurityContenxt.getLoginToken();
        if (userPrinciple == null){
            throw new BusinessException("101","用户认证解析失败");
        }
        Integer userId = userPrinciple.getId();
        //2. 仓储层查询用户id对应用户详情
        UserBO userBO=userRepository.getUserById(userId);
        //3. 返回查询结果
        return userBO;
    }

    @Override
    public void bindUserTags(UserTagsParam param) throws BusinessException {
        //1.param userId 没传 从头获取认证
        UserPrinciple userPrinciple=LbsSecurityContenxt.getLoginToken();
        if (userPrinciple==null){
            throw new BusinessException("101","用户认证解析失败");
        }
        Integer id = userPrinciple.getId();
        //2.处理一下tags数据 2,3,4 变成 [2,3,4]
        List<UserTagsParam> userTags=new ArrayList<>();
        String[] tags=param.getTagIds().split(",");
        for (String tag : tags) {
            UserTagsParam userTagParam=new UserTagsParam();
            userTagParam.setUserId(userPrinciple.getId());
            userTagParam.setTagIds(tag);
            userTags.add(userTagParam);
        }
        //3.交给仓储层
        userTagsRepository.deleteUserTags(id);
        userTagsRepository.batchInsertUserTags(userTags);
        //4. 把用户的状态修改成1 update user set status=1 where userId=1
        userRepository.updateUserStatus(id,1);
    }

    @Override
    public BasePageList<UserGroupBO> userGroupPage(UserGroupQuery query) {
            return userGroupRepository.getUserGroupsByPage(query);
    }

    @Override
    public void saveUserGroup(UserGroupBO bo) throws BusinessException{
        UserPrinciple userPrinciple = LbsSecurityContenxt.getLoginToken();
        if (userPrinciple == null){
            throw new BusinessException("101","用户认证解析失败");
        }
        Integer adminId=userPrinciple.getId();
        AdminBO adminBO = adminService.adminDetail(adminId);
        if (ObjectUtils.isEmpty(adminBO)){
            throw new BusinessException("107","当前商家账号不存在");
        }
        Integer businessId = adminBO.getBusinessId();
        bo.setBusinessId(businessId);
        bo.setCreateAt(LocalDateTime.now());
        userGroupRepository.saveUserGroup(bo);
    }

    @Override
    public boolean isUserGroup(Integer userId, Integer groupId) {
        //利用userId 查询 lbs_user_tags 绑定标签列表
        List<Integer> userTagIds=userTagsRepository.getTagsByUserId(userId);
        if (CollectionUtils.isEmpty(userTagIds)){
            return false;
        }
        //userGroup
        String tagsStr=userGroupRepository.getGroupTagsById(groupId);
        if (StringUtils.isEmpty(tagsStr)){
            return false;
        }
        //做嵌套循环对比 有一个标签相等的 人群所属是true
        boolean result=false;
        String[] tagIds = tagsStr.split(",");
        for (String tagIdStr : tagIds) {
            Integer groupTagId=Integer.valueOf(tagIdStr);
            for (Integer userTagId : userTagIds) {
                if (userTagId==groupTagId){
                    result=true;
                    break;
                }
            }
        }
        return result;
    }
}
